package concurrent.lock;

import org.junit.Test;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockTest {

	@Test
	public void test() throws InterruptedException {
		
		final Lock lock = new ReentrantLock(true);
		new Thread(){
			@Override
			public void run() {
				lock.lock();
			}
		}.start();
		Thread.sleep(1000);
		new Thread(){
			@Override
			public void run() {
				System.out.println(lock.tryLock());
			}
		}.start();
	}

	@Test
	public void conditionTest() throws InterruptedException {

		ReentrantLock lock = new ReentrantLock();
		Condition condition = lock.newCondition();

		new Thread() {
			@Override
			public void run() {
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				lock.lock();
				System.out.println("子线程呼唤主线程并持有锁3秒钟。。。");
				condition.signal(); //调用await和signal必须获取到lock
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("子线程释放锁");
				lock.unlock();
			}
		}.start();

		lock.lock();
		System.out.println("主线程开始睡眠");
		condition.await(); //调用await和signal必须获取到lock，睡眠之后释放锁
		lock.unlock();
		System.out.println("主线程结束睡眠");
	}
}
